home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / multiprocessing / forking.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  13.9 KB  |  388 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import os
  5. import sys
  6. import signal
  7. from multiprocessing import util, process
  8. __all__ = [
  9.     'Popen',
  10.     'assert_spawning',
  11.     'exit',
  12.     'duplicate',
  13.     'close',
  14.     'ForkingPickler']
  15.  
  16. def assert_spawning(self):
  17.     if not Popen.thread_is_spawning():
  18.         raise RuntimeError('%s objects should only be shared between processes through inheritance' % type(self).__name__)
  19.     Popen.thread_is_spawning()
  20.  
  21. from pickle import Pickler
  22.  
  23. class ForkingPickler(Pickler):
  24.     dispatch = Pickler.dispatch.copy()
  25.     
  26.     def register(cls, type, reduce):
  27.         
  28.         def dispatcher(self, obj):
  29.             rv = reduce(obj)
  30.             self.save_reduce(obj = obj, *rv)
  31.  
  32.         cls.dispatch[type] = dispatcher
  33.  
  34.     register = classmethod(register)
  35.  
  36.  
  37. def _reduce_method(m):
  38.     if m.im_self is None:
  39.         return (getattr, (m.im_class, m.im_func.func_name))
  40.     return (getattr, (m.im_self, m.im_func.func_name))
  41.  
  42. ForkingPickler.register(type(ForkingPickler.save), _reduce_method)
  43.  
  44. def _reduce_method_descriptor(m):
  45.     return (getattr, (m.__objclass__, m.__name__))
  46.  
  47. ForkingPickler.register(type(list.append), _reduce_method_descriptor)
  48. ForkingPickler.register(type(int.__add__), _reduce_method_descriptor)
  49.  
  50. try:
  51.     from functools import partial
  52. except ImportError:
  53.     pass
  54.  
  55.  
  56. def _reduce_partial(p):
  57.     if not p.keywords:
  58.         pass
  59.     return (_rebuild_partial, (p.func, p.args, { }))
  60.  
  61.  
  62. def _rebuild_partial(func, args, keywords):
  63.     return partial(func, *args, **keywords)
  64.  
  65. ForkingPickler.register(partial, _reduce_partial)
  66. if sys.platform != 'win32':
  67.     import time
  68.     exit = os._exit
  69.     duplicate = os.dup
  70.     close = os.close
  71.     
  72.     class Popen(object):
  73.         
  74.         def __init__(self, process_obj):
  75.             sys.stdout.flush()
  76.             sys.stderr.flush()
  77.             self.returncode = None
  78.             self.pid = os.fork()
  79.             if self.pid == 0:
  80.                 if 'random' in sys.modules:
  81.                     import random
  82.                     random.seed()
  83.                 
  84.                 code = process_obj._bootstrap()
  85.                 sys.stdout.flush()
  86.                 sys.stderr.flush()
  87.                 os._exit(code)
  88.             
  89.  
  90.         
  91.         def poll(self, flag = os.WNOHANG):
  92.             if self.returncode is None:
  93.                 (pid, sts) = os.waitpid(self.pid, flag)
  94.                 if pid == self.pid:
  95.                     if os.WIFSIGNALED(sts):
  96.                         self.returncode = -os.WTERMSIG(sts)
  97.                     elif not os.WIFEXITED(sts):
  98.                         raise AssertionError
  99.                     self.returncode = os.WEXITSTATUS(sts)
  100.                 
  101.             
  102.             return self.returncode
  103.  
  104.         
  105.         def wait(self, timeout = None):
  106.             if timeout is None:
  107.                 return self.poll(0)
  108.             deadline = time.time() + timeout
  109.             delay = 0.0005
  110.             while None:
  111.                 res = self.poll()
  112.                 if res is not None:
  113.                     break
  114.                 
  115.                 remaining = deadline - time.time()
  116.                 if remaining <= 0:
  117.                     break
  118.                 
  119.                 delay = min(delay * 2, remaining, 0.05)
  120.                 continue
  121.                 return res
  122.  
  123.         
  124.         def terminate(self):
  125.             if self.returncode is None:
  126.                 
  127.                 try:
  128.                     os.kill(self.pid, signal.SIGTERM)
  129.                 except OSError:
  130.                     e = None
  131.                     if self.wait(timeout = 0.1) is None:
  132.                         raise 
  133.                     self.wait(timeout = 0.1) is None
  134.                 except:
  135.                     None<EXCEPTION MATCH>OSError
  136.                 
  137.  
  138.             None<EXCEPTION MATCH>OSError
  139.  
  140.         
  141.         def thread_is_spawning():
  142.             return False
  143.  
  144.         thread_is_spawning = staticmethod(thread_is_spawning)
  145.  
  146. else:
  147.     import thread
  148.     import msvcrt
  149.     import _subprocess
  150.     import time
  151.     from _multiprocessing import win32, Connection, PipeConnection
  152.     from util import Finalize
  153.     from pickle import load, HIGHEST_PROTOCOL
  154.     
  155.     def dump(obj, file, protocol = None):
  156.         ForkingPickler(file, protocol).dump(obj)
  157.  
  158.     TERMINATE = 65536
  159.     if sys.platform == 'win32':
  160.         pass
  161.     WINEXE = getattr(sys, 'frozen', False)
  162.     exit = win32.ExitProcess
  163.     close = win32.CloseHandle
  164.     if sys.executable.lower().endswith('pythonservice.exe'):
  165.         _python_exe = os.path.join(sys.exec_prefix, 'python.exe')
  166.     else:
  167.         _python_exe = sys.executable
  168.     
  169.     def set_executable(exe):
  170.         global _python_exe
  171.         _python_exe = exe
  172.  
  173.     
  174.     def duplicate(handle, target_process = None, inheritable = False):
  175.         if target_process is None:
  176.             target_process = _subprocess.GetCurrentProcess()
  177.         
  178.         return _subprocess.DuplicateHandle(_subprocess.GetCurrentProcess(), handle, target_process, 0, inheritable, _subprocess.DUPLICATE_SAME_ACCESS).Detach()
  179.  
  180.     
  181.     class Popen(object):
  182.         '''
  183.         Start a subprocess to run the code of a process object
  184.         '''
  185.         _tls = thread._local()
  186.         
  187.         def __init__(self, process_obj):
  188.             (rfd, wfd) = os.pipe()
  189.             rhandle = duplicate(msvcrt.get_osfhandle(rfd), inheritable = True)
  190.             os.close(rfd)
  191.             cmd = get_command_line() + [
  192.                 rhandle]
  193.             cmd = ' '.join((lambda .0: for x in .0:
  194. '"%s"' % x)(cmd))
  195.             (hp, ht, pid, tid) = _subprocess.CreateProcess(_python_exe, cmd, None, None, 1, 0, None, None, None)
  196.             ht.Close()
  197.             close(rhandle)
  198.             self.pid = pid
  199.             self.returncode = None
  200.             self._handle = hp
  201.             prep_data = get_preparation_data(process_obj._name)
  202.             to_child = os.fdopen(wfd, 'wb')
  203.             Popen._tls.process_handle = int(hp)
  204.             
  205.             try:
  206.                 dump(prep_data, to_child, HIGHEST_PROTOCOL)
  207.                 dump(process_obj, to_child, HIGHEST_PROTOCOL)
  208.             finally:
  209.                 del Popen._tls.process_handle
  210.                 to_child.close()
  211.  
  212.  
  213.         
  214.         def thread_is_spawning():
  215.             return getattr(Popen._tls, 'process_handle', None) is not None
  216.  
  217.         thread_is_spawning = staticmethod(thread_is_spawning)
  218.         
  219.         def duplicate_for_child(handle):
  220.             return duplicate(handle, Popen._tls.process_handle)
  221.  
  222.         duplicate_for_child = staticmethod(duplicate_for_child)
  223.         
  224.         def wait(self, timeout = None):
  225.             if self.returncode is None:
  226.                 if timeout is None:
  227.                     msecs = _subprocess.INFINITE
  228.                 else:
  229.                     msecs = max(0, int(timeout * 1000 + 0.5))
  230.                 res = _subprocess.WaitForSingleObject(int(self._handle), msecs)
  231.                 if res == _subprocess.WAIT_OBJECT_0:
  232.                     code = _subprocess.GetExitCodeProcess(self._handle)
  233.                     if code == TERMINATE:
  234.                         code = -(signal.SIGTERM)
  235.                     
  236.                     self.returncode = code
  237.                 
  238.             
  239.             return self.returncode
  240.  
  241.         
  242.         def poll(self):
  243.             return self.wait(timeout = 0)
  244.  
  245.         
  246.         def terminate(self):
  247.             if self.returncode is None:
  248.                 
  249.                 try:
  250.                     _subprocess.TerminateProcess(int(self._handle), TERMINATE)
  251.                 except WindowsError:
  252.                     if self.wait(timeout = 0.1) is None:
  253.                         raise 
  254.                     self.wait(timeout = 0.1) is None
  255.                 except:
  256.                     None<EXCEPTION MATCH>WindowsError
  257.                 
  258.  
  259.             None<EXCEPTION MATCH>WindowsError
  260.  
  261.  
  262.     
  263.     def is_forking(argv):
  264.         '''
  265.         Return whether commandline indicates we are forking
  266.         '''
  267.         if len(argv) >= 2 and argv[1] == '--multiprocessing-fork':
  268.             if not len(argv) == 3:
  269.                 raise AssertionError
  270.             return True
  271.         return False
  272.  
  273.     
  274.     def freeze_support():
  275.         '''
  276.         Run code for process object if this in not the main process
  277.         '''
  278.         if is_forking(sys.argv):
  279.             main()
  280.             sys.exit()
  281.         
  282.  
  283.     
  284.     def get_command_line():
  285.         '''
  286.         Returns prefix of command line used for spawning a child process
  287.         '''
  288.         if process.current_process()._identity == () and is_forking(sys.argv):
  289.             raise RuntimeError('\n            Attempt to start a new process before the current process\n            has finished its bootstrapping phase.\n\n            This probably means that you are on Windows and you have\n            forgotten to use the proper idiom in the main module:\n\n                if __name__ == \'__main__\':\n                    freeze_support()\n                    ...\n\n            The "freeze_support()" line can be omitted if the program\n            is not going to be frozen to produce a Windows executable.')
  290.         is_forking(sys.argv)
  291.         if getattr(sys, 'frozen', False):
  292.             return [
  293.                 sys.executable,
  294.                 '--multiprocessing-fork']
  295.         prog = 'from multiprocessing.forking import main; main()'
  296.         return [
  297.             _python_exe,
  298.             '-c',
  299.             prog,
  300.             '--multiprocessing-fork']
  301.  
  302.     
  303.     def main():
  304.         '''
  305.         Run code specifed by data received over pipe
  306.         '''
  307.         if not is_forking(sys.argv):
  308.             raise AssertionError
  309.         handle = int(sys.argv[-1])
  310.         fd = msvcrt.open_osfhandle(handle, os.O_RDONLY)
  311.         from_parent = os.fdopen(fd, 'rb')
  312.         process.current_process()._inheriting = True
  313.         preparation_data = load(from_parent)
  314.         prepare(preparation_data)
  315.         self = load(from_parent)
  316.         process.current_process()._inheriting = False
  317.         from_parent.close()
  318.         exitcode = self._bootstrap()
  319.         exit(exitcode)
  320.  
  321.     
  322.     def get_preparation_data(name):
  323.         '''
  324.         Return info about parent needed by child to unpickle process object
  325.         '''
  326.         _logger = _logger
  327.         _log_to_stderr = _log_to_stderr
  328.         import util
  329.         d = dict(name = name, sys_path = sys.path, sys_argv = sys.argv, log_to_stderr = _log_to_stderr, orig_dir = process.ORIGINAL_DIR, authkey = process.current_process().authkey)
  330.         if _logger is not None:
  331.             d['log_level'] = _logger.getEffectiveLevel()
  332.         
  333.         if not WINEXE:
  334.             main_path = getattr(sys.modules['__main__'], '__file__', None)
  335.             if not main_path and sys.argv[0] not in ('', '-c'):
  336.                 main_path = sys.argv[0]
  337.             
  338.             if main_path is not None:
  339.                 if not os.path.isabs(main_path) and process.ORIGINAL_DIR is not None:
  340.                     main_path = os.path.join(process.ORIGINAL_DIR, main_path)
  341.                 
  342.                 d['main_path'] = os.path.normpath(main_path)
  343.             
  344.         
  345.         return d
  346.  
  347.     
  348.     def reduce_connection(conn):
  349.         if not Popen.thread_is_spawning():
  350.             raise RuntimeError('By default %s objects can only be shared between processes\nusing inheritance' % type(conn).__name__)
  351.         Popen.thread_is_spawning()
  352.         return (type(conn), (Popen.duplicate_for_child(conn.fileno()), conn.readable, conn.writable))
  353.  
  354.     ForkingPickler.register(Connection, reduce_connection)
  355.     ForkingPickler.register(PipeConnection, reduce_connection)
  356. old_main_modules = []
  357.  
  358. def prepare(data):
  359.     '''
  360.     Try to get current process ready to unpickle process object
  361.     '''
  362.     old_main_modules.append(sys.modules['__main__'])
  363.     if 'name' in data:
  364.         process.current_process().name = data['name']
  365.     
  366.     if 'authkey' in data:
  367.         process.current_process()._authkey = data['authkey']
  368.     
  369.     if 'log_to_stderr' in data and data['log_to_stderr']:
  370.         util.log_to_stderr()
  371.     
  372.     if 'log_level' in data:
  373.         util.get_logger().setLevel(data['log_level'])
  374.     
  375.     if 'sys_path' in data:
  376.         sys.path = data['sys_path']
  377.     
  378.     if 'sys_argv' in data:
  379.         sys.argv = data['sys_argv']
  380.     
  381.     if 'dir' in data:
  382.         os.chdir(data['dir'])
  383.     
  384.     if 'orig_dir' in data:
  385.         process.ORIGINAL_DIR = data['orig_dir']
  386.     
  387.  
  388.